import json
from rest_framework import serializers
from ..models.Literature import Literature
from django.contrib.contenttypes.models import ContentType
from ..models.Publications import Journal, Conference, Book
from ..utils.literUtils import emptyValue

# 查询内容序列化
class LiterListQuerySerializer(serializers.Serializer):
    title = serializers.CharField(required=False,allow_blank=True)
    zh_title = serializers.CharField(required=False,allow_blank=True)
    date = serializers.CharField(required=False,allow_blank=True)
    language = serializers.ListField(required=False)
    doi = serializers.CharField(required=False,allow_blank=True)
    authors = serializers.CharField(required=False,allow_blank=True)
    keywords = serializers.CharField(required=False,allow_blank=True)
    abstract = serializers.CharField(required=False,allow_blank=True)
    status = serializers.ListField(required=False)
    liter_code = serializers.CharField(required=False,allow_blank=True)
    comment = serializers.CharField(required=False,allow_blank=True)
    founder_info = serializers.CharField(required=False,allow_blank=True)
    net_src = serializers.CharField(required=False,allow_blank=True)
    liter_type = serializers.ListField(required=False) # 引文类型
    pub_type = serializers.ListField(required=False)
    pub_name = serializers.CharField(required=False,allow_blank=True)
    volume = serializers.CharField(required=False,allow_blank=True)
    issue = serializers.CharField(required=False,allow_blank=True)
    edition_number = serializers.CharField(required=False,allow_blank=True)
    first_page = serializers.CharField(required=False,allow_blank=True)
    last_page = serializers.CharField(required=False,allow_blank=True)
    cit_name = serializers.CharField(required=False,allow_blank=True)
    cit_id = serializers.CharField(required=False,allow_blank=True)
    cited_count = serializers.CharField(required=False,allow_blank=True)
    cited_list = serializers.CharField(required=False,allow_blank=True)

    page_size = serializers.IntegerField(
        required=False, max_value=50, min_value=1)
    current_page = serializers.IntegerField(required=False)
    sort_prop = serializers.CharField(required=False,allow_blank=True)
    sort_order = serializers.CharField(required=False,allow_blank=True)

    def validate(self, attrs):
        filter_flag = True
        page_flag = True
        if "title" in attrs:
            attrs["title"] = attrs["title"].strip()
            if attrs["title"] == "": attrs.pop("title")
        if "zh_title" in attrs:
            attrs["zh_title"] = attrs["zh_title"].strip()
            if attrs["zh_title"] == "": attrs.pop("zh_title")
        if "date" in attrs:
            attrs["date"] = attrs["date"].strip()
            if attrs["date"] == "": attrs.pop("date")
        if "abstract" in attrs:
            attrs["abstract"] = attrs["abstract"].strip()
            if attrs["abstract"] == "": attrs.pop("abstract")
        if "doi" in attrs:
            attrs["doi"] = attrs["doi"].strip()
            if attrs["doi"] == "": attrs.pop("doi")
        if "liter_code" in attrs:
            attrs["liter_code"] = attrs["liter_code"].strip()
            if attrs["liter_code"] == "": attrs.pop("liter_code")
        if "net_src" in attrs:
            attrs["net_src"] = attrs["net_src"].strip()
            if attrs["net_src"] == "": attrs.pop("net_src")
        if "volume" in attrs:
            attrs["volume"] = attrs["volume"].strip()
            if attrs["volume"] == "": attrs.pop("volume")
        if "issue" in attrs:
            attrs["issue"] = attrs["issue"].strip()
            if attrs["issue"] == "": attrs.pop("issue")
        if "edition_number" in attrs:
            attrs["edition_number"] = attrs["edition_number"].strip()
            if attrs["edition_number"] == "": attrs.pop("edition_number")
        if "first_page" in attrs:
            attrs["first_page"] = attrs["first_page"].strip()
            if attrs["first_page"] == "": attrs.pop("first_page")
        if "last_page" in attrs:
            attrs["last_page"] = attrs["last_page"].strip()
            if attrs["last_page"] == "": attrs.pop("last_page")
        if "founder_info" in attrs:
            attrs["founder_info"] = attrs["founder_info"].strip()
            if attrs["founder_info"] == "": attrs.pop("founder_info")
        if "comment" in attrs:
            attrs["comment"] = attrs["comment"].strip()
            if attrs["comment"] == "": attrs.pop("comment")
        if "cit_name" in attrs:
            attrs["cit_name"] = attrs["cit_name"].strip()
            if attrs["cit_name"] == "": attrs.pop("cit_name")
        if "cit_id" in attrs:
            attrs["cit_id"] = attrs["cit_id"].strip()
            if attrs["cit_id"] == "": attrs.pop("cit_id")
        if "cited_count" in attrs:
            attrs["cited_count"] = attrs["cited_count"].strip()
            if attrs["cited_count"] == "": attrs.pop("cited_count")
        if "pub_name" in attrs:
            attrs["pub_name"] = attrs["pub_name"].strip()
            if attrs["pub_name"] == "": attrs.pop("pub_name")
        if "authors" in attrs:
            attrs["authors"] = attrs["authors"].strip()
            if attrs["authors"] == "": attrs.pop("authors")
        if "keywords" in attrs:
            attrs["keywords"] = attrs["keywords"].strip()
            if attrs["keywords"] == "": attrs.pop("keywords")
        if "cited_list" in attrs:
            attrs["cited_list"] = attrs["cited_list"].strip()
            if attrs["cited_list"] == "": attrs.pop("cited_list")
        if "language" in attrs:
            if len(attrs["language"]) == 0: attrs.pop("language")
        if "status" in attrs:
            if len(attrs["status"]) == 0: attrs.pop("status")
        if "liter_type" in attrs:
            if len(attrs["liter_type"]) == 0: attrs.pop("liter_type")
        if "pub_type" in attrs:
            if len(attrs["pub_type"]) == 0: attrs.pop("pub_type")
        if ("title" not in attrs or attrs["title"] == "") and ("zh_title" not in attrs or attrs["zh_title"] == "") and\
           ("date" not in attrs or attrs["date"] == "") and ("language" not in attrs or len(attrs["language"]) == 0) and\
           ("doi" not in attrs or attrs["doi"] == "") and ("authors" not in attrs or attrs["authors"] == "")  and\
           ("keywords" not in attrs or attrs["keywords"] == "") and ("abstract" not in attrs or attrs["abstract"] == "")  and\
           ("status" not in attrs or len(attrs["status"]) == 0) and ("comment" not in attrs or attrs["comment"] == "") and\
           ("founder_info" not in attrs or attrs["founder_info"] == "") and ("net_src" not in attrs or attrs["net_src"] == "") and\
           ("liter_type" not in attrs or len(attrs["liter_type"]) == 0) and ("pub_type" not in attrs or len(attrs["pub_type"]) == 0) and \
           ("pub_name" not in attrs or attrs["pub_name"] == "") and ("volume" not in attrs or attrs["volume"] == "") and\
           ("issue" not in attrs or attrs["issue"] == "") and ("edition_number" not in attrs or attrs["edition_number"] == "") and\
           ("first_page" not in attrs or attrs["first_page"] == "") and ("last_page" not in attrs or attrs["last_page"] == "") and\
           ("cit_name" not in attrs or attrs["cit_name"] == "") and ("cit_id" not in attrs or attrs["cit_id"] == "") and\
           ("cited_count" not in attrs or attrs["cited_count"] == "") and ("cited_list" not in attrs or attrs["cited_list"] == "") and\
           ("liter_code" not in attrs or attrs["liter_code"] == ""):
            filter_flag = False
        if ("page_size" not in attrs):
            page_flag = False
        else:
            if "current_page" not in attrs:
                attrs["current_page"] = 1
        if not filter_flag and not page_flag:
            raise serializers.ValidationError({
                'detail': '查询条件过于宽泛'
            })
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError({
                'detail': '验证失败:' + str(e.detail)
            })
        return attrs
    
    @classmethod
    def get_query_fields(self):
        return [{"title":"引文名称：", "dataIndex":"title", "type":"CharField"},
                {"title":"引文中文名称：", "dataIndex":"zh_title", "type":"CharField"},
                {"title":"作者列表：", "dataIndex":"authors", "type":"ManyToManyField"},
                {"title":"关键词列表：", "dataIndex":"keywords", "type":"ManyToManyField"},
                {"title":"发表日期：", "dataIndex":"date", "type":"CharField"},
                {"title":"摘要：", "dataIndex":"abstract", "type":"CharField"},
                {"title":"语言：", "dataIndex":"language", "type":"ForeignKey"},
                {"title":"DOI：", "dataIndex":"doi", "type":"CharField"},
                {"title":"引文编码：", "dataIndex":"liter_code", "type":"CharField"},
                {"title":"网络链接：", "dataIndex":"net_src", "type":"CharField"},
                {"title":"引文类型：", "dataIndex":"liter_type", "type":"ForeignKey"},
                {"title":"来源类型：", "dataIndex":"pub_type", "type":"ForeignKey"},
                {"title":"来源出版物：", "dataIndex":"pub_name", "type":"CharField"},
                {"title":"卷号：", "dataIndex":"volume", "type":"CharField"},
                {"title":"期号：", "dataIndex":"issue", "type":"CharField"},
                {"title":"版次：", "dataIndex":"edition_number", "type":"CharField"},
                {"title":"起始页码：", "dataIndex":"first_page", "type":"CharField"},
                {"title":"结束页码：", "dataIndex":"last_page", "type":"CharField"},
                {"title":"文献状态：", "dataIndex":"status", "type":"ForeignKey"},
                {"title":"资助方信息：", "dataIndex":"founder_info", "type":"CharField"},
                {"title":"备注评论：", "dataIndex":"comment", "type":"CharField"},
                {"title":"来源数据库名称：", "dataIndex":"cit_name", "type":"CharField"},
                {"title":"来源库中编号：", "dataIndex":"cit_id", "type":"CharField"},
                {"title":"被引用数：", "dataIndex":"cited_count", "type":"CharField"},
                {"title":"引用文献：", "dataIndex":"cited_list", "type":"ManyToManyField"},]
        
        
# 用于输出查询时的数据


class LiterListSerializer(serializers.ModelSerializer):
    liter_type = serializers.SerializerMethodField()
    pub_name = serializers.SerializerMethodField()
    language = serializers.SerializerMethodField()
    authors = serializers.SerializerMethodField()
    keywords = serializers.SerializerMethodField()
    status = serializers.SerializerMethodField()
    net_src_state = serializers.SerializerMethodField()
    cited_list = serializers.SerializerMethodField()
    pub_type = serializers.SerializerMethodField()

    class Meta:
        model = Literature
        fields = ['uuid', 'title', 'zh_title', 'liter_code', "authors", "keywords", 'date', 'abstract', 'language', 'DOI', "liter_type", "pub_type", "pub_name", \
                  "volume", 'issue', "first_page", 'last_page', 'edition_number', "net_src", "net_src_state", "db_src", \
                  'status', 'founder_info', "comment", 'cit_name', 'cit_id', 'cited_count', 'cited_list']
        
    def get_liter_type(self, obj): # obj: Literature类实例
        return "{}({})".format(obj.liter_type.zh_name, obj.liter_type.name) + "\n"
    
    def get_pub_type(self, obj):
        if obj.pub_type == 'unknown':
            return "未知"
        elif obj.pub_type == 'Journal':
            return "期刊(Journal)"
        elif obj.pub_type == 'Book':
            return "书籍(Book)"
        elif obj.pub_type == 'Conference':
            return "会议(Conference)"
        else:
            return "错误类型"
    
    def get_pub_name(self, obj):
        if obj.pub_id is None:
            return "未知"
        elif emptyValue(obj.pub_id.zh_name):
            return "{}".format(obj.pub_id.name) + "\n"
        else:
            return "{}({})".format(obj.pub_id.zh_name, obj.pub_id.name) + "\n"
    
    def get_language(self, obj):
        return "{}({})".format(obj.language.zh_name, obj.language.name) + "\n"
    
    def get_net_src_state(self, obj):
        return "是" if obj.net_src_state == True else "否"
    
    def get_status(self, obj):
        return "{}({})".format(obj.status.zh_name, obj.status.name) + "\n"
    
    def get_authors(self, obj):
        authors_content = ""
        for author in obj.authors.all():
            if emptyValue(author.zh_name):
                authors_content += author.name + "; "
            else:
                authors_content += author.name + ' (' + author.zh_name + '); '
        return authors_content[:-2]
    
    def get_keywords(self, obj):
        keywords_content = ""
        for keyword in obj.keywords.all():
            if emptyValue(keyword.v):
                keywords_content += keyword.k + '; '
            else:
                keywords_content += keyword.k + ' (' + keyword.v + '); '
        return keywords_content[:-2]
    
    def get_cited_list(self, obj):
        cited_list_content = ""
        for cit_liter in obj.cited_list.all():
            cited_list_content += cit_liter.title + ' (' + cit_liter.zh_title + '); '
        return cited_list_content[:-2]
        
    @classmethod
    def get_extra_fields_info(self):
        return [{"title":"引文名称", "dataIndex":"title", "type":"TextField"},
                {"title":"引文中文名称", "dataIndex":"zh_title", "type":"TextField"},
                {"title":"引文类型", "dataIndex":"liter_type", "type":"CharField"},
                {"title":"来源类型", "dataIndex":"pub_type", "type":"CharField"},
                {"title":"来源出版物名称", "dataIndex":"pub_name", "type":"TextField"},
                {"title":"语言", "dataIndex":"language", "type":"CharField"},
                {"title":"作者列表", "dataIndex":"authors", "type":"TextField"},
                {"title":"关键词列表", "dataIndex":"keywords", "type":"TextField"},
                {"title":"引用文献", "dataIndex":"cited_list", "type":"TextField"},
                {"title":"网络链接", "dataIndex":"net_src", "type":"TextField"},
                {"title":"DOI", "dataIndex":"DOI", "type":"TextField"},
                {"title":"数据库存储路径", "dataIndex":"db_src", "type":"TextField"},]